<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>智慧校园生活管理系统</span>
        </div>
      </template>
      <!-- 添加ref属性绑定表单引用 -->
      <el-form ref="formRef" :model="loginForm" :rules="rules" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" block>登录</el-button>
        </el-form-item>
        <div class="login-footer">
          <span>还没有账号？</span>
          <router-link to="/register" class="register-link">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userApi } from '../api'
import { setToken, setUserInfo } from '../utils/auth'

// 登录表单数据
const loginForm = ref({ username: '', password: '' })

// 表单引用
const formRef = ref(null)

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 加载状态
const loading = ref(false)

// 路由实例
const router = useRouter()

// 处理登录
const handleLogin = async () => {
  try {
    // 使用ref获取表单引用进行验证
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          console.log('提交登录请求:', loginForm.value)
          // 调用登录API
          const response = await userApi.login(loginForm.value)
          console.log('登录响应:', response)
          console.log('登录响应data:', response.data)
          console.log('登录响应结构:', JSON.stringify(response))
          
          // 尝试多种方式获取token
          let token = null
          // 方式1: 从data.tokens.access获取（根据控制台输出的正确路径）
          if (response.data && response.data.tokens && response.data.tokens.access) {
            token = response.data.tokens.access
          }
          // 方式2: 从data.access获取
          else if (response.data && response.data.access) {
            token = response.data.access
          }
          // 方式3: 从data.token获取
          else if (response.data && response.data.token) {
            token = response.data.token
          }
          // 方式4: 从响应体顶层获取
          else if (response.access) {
            token = response.access
          }
          else if (response.token) {
            token = response.token
          }

          if (!token) {
            throw new Error(`登录失败: 未获取到token。响应数据: ${JSON.stringify(response)}`)
          }

          // 存储token和用户信息
          setToken(token)
          // 存储用户信息
          const userInfo = { username: loginForm.value.username }
          setUserInfo(userInfo)

          // 显示成功消息
          ElMessage.success('登录成功')
          // 跳转到首页
          router.push('/')
        } catch (error) {
          console.error('登录API错误:', error)
          // 显示详细错误信息
          const errorMsg = error.response?.data?.message || error.message || '登录失败，请重试'
          ElMessage.error(errorMsg)
        } finally {
          loading.value = false
        }
      }
    })
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请重试')
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

.login-form {
  padding: 20px;
}

.login-footer {
  text-align: center;
  margin-top: 15px;
}

.register-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.register-link:hover {
  text-decoration: underline;
}

/* 增强输入框样式，确保文字可见 */
:deep(.el-input) {
  --el-input-text-color: #333 !important;
}

:deep(.el-input__input) {
  color: #333 !important;
  background-color: #fff !important;
  border: 1px solid #dcdfe6 !important;
  opacity: 1 !important;
  text-shadow: none !important;
  -webkit-text-fill-color: #333 !important;
  -webkit-text-stroke: 0 !important;
  font-size: 16px !important;
  font-family: Arial, sans-serif !important;
}

/* 聚焦状态 */
:deep(.el-input__input:focus) {
  color: #333 !important;
}

/* 修复暗模式下的显示问题 */
@media (prefers-color-scheme: dark) {
  :deep(.el-input) {
    --el-input-text-color: #fff !important;
  }

  :deep(.el-input__input) {
    color: #fff !important;
    background-color: #303030 !important;
    -webkit-text-fill-color: #fff !important;
  }
}
</style>